package org.teachertools.web.struts;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.springframework.beans.factory.annotation.Configurable;
import org.teachertools.web.ServiceLocator;

@Configurable
// Remlpacer les frames par des div et des CSS
public abstract class BaseAction extends Action {

    protected static final String SUCCESS = "success";
    protected static final String ERROR = "error";
    protected static final String CONTINUE = "continue";

    protected Log log = LogFactory.getLog(getClass());

    @Resource
    private ServiceLocator serviceLocator;

    protected ServiceLocator getServiceLocator() {
        return this.serviceLocator;
    }

    protected String getMessage(HttpServletRequest request, String key) {
        MessageResources messageResources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
        return messageResources.getMessage(key);
    }

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            return process(mapping, form, request, response);
        } catch (ProcessException ex) {
            return handleError(mapping, "Can't execute preprocess method for action", ex);
        } catch (Exception ex) {
            return handleError(mapping, "Can't execute action", ex);
        }
    }

    /**
     * Return a forward "error"
     */
    private ActionForward handleError(ActionMapping mapping, String msg, Exception e) throws Exception {
        this.log.error(msg + " " + mapping.getName(), e);
        ActionForward forward = mapping.findForward(ERROR);
        if (forward != null) {
            return forward;
        }
        throw e;
    }

    protected abstract ActionForward process(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception;
}